<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统设置 - DTU管理系统</title>
    <script src="js/toast.js"></script>
    <link rel="stylesheet" href="css/common.css">
    <style>
        .danger-zone {
            border: 2px solid #dc3545;
            border-radius: 6px;
            padding: 1.5rem;
            margin-top: 1rem;
        }
        
        .danger-zone h4 {
            color: #dc3545;
            margin-bottom: 1rem;
        }
        
        .danger-zone p {
            color: #721c24;
            margin-bottom: 1rem;
            font-size: 0.9rem;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>系统设置</h1>
        <div class="breadcrumb">DTU管理系统 / 系统设置</div>
    </div>

    <div class="container">
        <!-- Tab导航 -->
        <div class="nav-tabs">
            <a href="index.html" class="nav-tab">首页</a>
            <a href="network.html" class="nav-tab">网络配置</a>
            <a href="serial.html" class="nav-tab">串口配置</a>
            <a href="collect.html" class="nav-tab">数据采集</a>
            <a href="push.html" class="nav-tab">数据推送</a>
            <a href="at-command.html" class="nav-tab">AT命令</a>
            <a href="system.html" class="nav-tab active">系统设置</a>
        </div>
        
        <!-- 设备信息配置 -->
        <div class="config-section">
            <h3>设备信息配置</h3>
            <form id="device-form">
                <div class="form-row">
                    <div class="form-group">
                        <label for="device-id">设备ID</label>
                        <input type="text" id="device-id" value="DTU001" placeholder="设备唯一标识">
                    </div>
                    <div class="form-group">
                        <label for="device-serial">设备序列号</label>
                        <input type="text" id="device-serial" value="SN123456789" placeholder="设备序列号">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="device-description">设备描述</label>
                        <input type="text" id="device-description" placeholder="设备描述信息">
                    </div>
                    <div class="form-group">
                        <label for="device-location">设备位置</label>
                        <input type="text" id="device-location" placeholder="设备安装位置">
                    </div>
                </div>
                <button type="button" class="btn btn-primary" onclick="saveDeviceInfo()">保存设备信息</button>
            </form>
        </div>

        <!-- 系统操作 -->
        <div class="config-section">
            <h3>系统操作</h3>
            <!-- 危险操作区域 -->
            <div class="danger-zone">
                <h4>危险操作</h4>
                <p>以下操作可能导致数据丢失或系统不稳定，请谨慎操作。</p>
                <button type="button" class="btn btn-danger" onclick="restartSystem()">重启系统</button>
                <button type="button" class="btn btn-danger" onclick="factoryReset()">恢复出厂设置</button>
                <button type="button" class="btn btn-danger" onclick="formatStorage()">格式化存储</button>
            </div>
        </div>

        <!-- 时间设置 -->
        <div class="config-section">
            <h3>时间设置</h3>
            <form id="time-form">
                <div class="form-row">
                    <div class="form-group">
                        <label for="timezone">时区设置</label>
                        <select id="timezone">
                            <option value="UTC+8" selected>UTC+8 (北京时间)</option>
                            <option value="UTC+0">UTC+0 (格林威治时间)</option>
                            <option value="UTC-5">UTC-5 (纽约时间)</option>
                            <option value="UTC+9">UTC+9 (东京时间)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="ntp-server">NTP服务器</label>
                        <input type="text" id="ntp-server" value="pool.ntp.org" placeholder="NTP服务器地址">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="current-time">当前时间</label>
                        <input type="datetime-local" id="current-time" readonly>
                    </div>
                    <div class="form-group">
                        <label>时间同步</label>
                        <div>
                            <button type="button" class="btn btn-secondary" onclick="syncTime()">同步时间</button>
                        </div>
                    </div>
                </div>
                <button type="button" class="btn btn-primary" onclick="saveTimeConfig()">保存时间设置</button>
            </form>
        </div>
    </div>

    <!-- Toast容器 -->
    <div class="toast-container" id="toast-container"></div>

    <script>

        // API请求封装
        async function apiRequest(url, method = 'GET', data = null) {
            try {
                const options = {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                    }
                };

                if (data) {
                    options.body = JSON.stringify(data);
                }

                const response = await fetch(url, options);
                const result = await response.json();

                if (!response.ok) {
                    throw new Error(result.error?.message || '请求失败');
                }

                return result;
            } catch (error) {
                console.error('API请求错误:', error);
                showMessage(error.message, 'danger');
                throw error;
            }
        }

        // 设备信息相关函数
        async function saveDeviceInfo() {
            const data = {
                device_id: document.getElementById('device-id').value,
                serial_number: document.getElementById('device-serial').value,
                description: document.getElementById('device-description').value,
                location: document.getElementById('device-location').value
            };

            try {
                await apiRequest('/api/system/device-info', 'POST', data);
                showMessage('设备信息保存成功');
            } catch (error) {
                showMessage('保存失败: ' + error.message, 'danger');
            }
        }

        // 系统操作相关函数
        async function restartSystem() {
            if (confirm('确定要重启系统吗？重启后需要重新连接。')) {
                try {
                    await apiRequest('/api/system/restart', 'POST');
                    showMessage('系统正在重启，请稍后重新连接...', 'info');
                } catch (error) {
                    showMessage('重启失败: ' + error.message, 'danger');
                }
            }
        }

        async function factoryReset() {
            const confirmText = prompt('此操作将清除所有配置并恢复出厂设置！\n请输入 "FACTORY_RESET" 确认操作：');
            if (confirmText === 'FACTORY_RESET') {
                try {
                    await apiRequest('/api/system/factory-reset', 'POST');
                    showMessage('正在恢复出厂设置...', 'info');
                } catch (error) {
                    showMessage('恢复出厂设置失败: ' + error.message, 'danger');
                }
            }
        }

        async function formatStorage() {
            const confirmText = prompt('此操作将格式化存储设备，所有数据将丢失！\n请输入 "FORMAT_STORAGE" 确认操作：');
            if (confirmText === 'FORMAT_STORAGE') {
                try {
                    await apiRequest('/api/system/format-storage', 'POST');
                    showMessage('正在格式化存储设备...', 'info');
                } catch (error) {
                    showMessage('格式化失败: ' + error.message, 'danger');
                }
            }
        }

        async function saveAllConfig() {
            try {
                await apiRequest('/api/system/save-config', 'POST');
                showMessage('所有配置保存成功');
            } catch (error) {
                showMessage('保存配置失败: ' + error.message, 'danger');
            }
        }

        async function clearLogs() {
            if (confirm('确定要清除系统日志吗？')) {
                try {
                    await apiRequest('/api/system/clear-logs', 'POST');
                    showMessage('系统日志已清除');
                } catch (error) {
                    showMessage('清除日志失败: ' + error.message, 'danger');
                }
            }
        }

        async function checkSystem() {
            try {
                showMessage('正在进行系统检查...', 'info');
                const result = await apiRequest('/api/system/check', 'POST');
                showMessage('系统检查完成：' + result.message);
            } catch (error) {
                showMessage('系统检查失败: ' + error.message, 'danger');
            }
        }

        // 配置管理相关函数
        async function exportConfig() {
            try {
                const response = await fetch('/api/system/export-config');
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `dtu-config-${new Date().toISOString().split('T')[0]}.json`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
                showMessage('配置导出成功');
            } catch (error) {
                showMessage('配置导出失败: ' + error.message, 'danger');
            }
        }

        function importConfig() {
            document.getElementById('config-file').click();
        }

        async function handleConfigImport(event) {
            const file = event.target.files[0];
            if (!file) return;

            try {
                const formData = new FormData();
                formData.append('config', file);
                
                const response = await fetch('/api/system/import-config', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    showMessage('配置导入成功');
                } else {
                    showMessage('配置导入失败: ' + result.error, 'danger');
                }
            } catch (error) {
                showMessage('配置导入失败: ' + error.message, 'danger');
            }
        }

        async function backupConfig() {
            try {
                await apiRequest('/api/system/backup-config', 'POST');
                showMessage('配置备份已创建');
            } catch (error) {
                showMessage('创建备份失败: ' + error.message, 'danger');
            }
        }

        async function restoreConfig() {
            if (confirm('确定要恢复配置备份吗？当前配置将被覆盖。')) {
                try {
                    await apiRequest('/api/system/restore-config', 'POST');
                    showMessage('配置恢复成功');
                } catch (error) {
                    showMessage('恢复配置失败: ' + error.message, 'danger');
                }
            }
        }

        // 时间设置相关函数
        async function saveTimeConfig() {
            const data = {
                timezone: document.getElementById('timezone').value,
                ntp_server: document.getElementById('ntp-server').value
            };

            try {
                await apiRequest('/api/system/time-config', 'POST', data);
                showMessage('时间设置保存成功');
            } catch (error) {
                showMessage('保存失败: ' + error.message, 'danger');
            }
        }

        async function syncTime() {
            try {
                showMessage('正在同步时间...', 'info');
                await apiRequest('/api/system/sync-time', 'POST');
                showMessage('时间同步成功');
                updateCurrentTime();
            } catch (error) {
                showMessage('时间同步失败: ' + error.message, 'danger');
            }
        }

        // 更新当前时间显示
        function updateCurrentTime() {
            const now = new Date();
            const timeString = now.toISOString().slice(0, 16);
            document.getElementById('current-time').value = timeString;
        }

        // 加载系统信息
        async function loadSystemInfo() {
            try {
                const info = await apiRequest('/api/system/info');
                updateSystemDisplay(info);
            } catch (error) {
                console.error('加载系统信息失败:', error);
            }
        }

        // 加载设备信息
        async function loadDeviceInfo() {
            try {
                const info = await apiRequest('/api/system/device-info');
                updateDeviceDisplay(info);
            } catch (error) {
                console.error('加载设备信息失败:', error);
            }
        }

        function updateSystemDisplay(info) {
            document.getElementById('firmware-version').textContent = info.firmware_version || 'v1.0.0';
            document.getElementById('hardware-version').textContent = info.hardware_version || 'v1.0';
            document.getElementById('system-uptime').textContent = info.uptime || '--';
            document.getElementById('memory-usage').textContent = info.memory_usage || '--';
            document.getElementById('cpu-usage').textContent = info.cpu_usage || '--';
            document.getElementById('storage-usage').textContent = info.storage_usage || '--';
        }

        function updateDeviceDisplay(info) {
            document.getElementById('device-id').value = info.device_id || 'DTU001';
            document.getElementById('device-serial').value = info.serial_number || 'SN123456789';
            document.getElementById('device-description').value = info.description || '';
            document.getElementById('device-location').value = info.location || '';
        }

        // 定时更新系统信息
        function startInfoRefresh() {
            setInterval(() => {
                loadSystemInfo();
                updateCurrentTime();
            }, 30000); // 每30秒更新一次
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('系统设置页面已加载');
            
            // 加载系统和设备信息
            loadSystemInfo();
            loadDeviceInfo();
            updateCurrentTime();
            
            // 启动定时刷新
            startInfoRefresh();
        });
    </script>
</body>
</html>